package com.woniuxy.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import com.woniuxy.entity.Perms1;

import com.woniuxy.entity.Role1;

import com.woniuxy.entity.User1;
import com.woniuxy.service.User1Service;


public class MyRealm extends AuthorizingRealm{
	//注入service
	@Autowired
	private User1Service userService;
	//用来从数据库中获取角色、权限信息
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//System.out.println("正在获取角色、权限信息....");
				//通过当前用户的账号去数据库中查询出当前用户的角色信息
				String account = (String)principals.getPrimaryPrincipal();
				System.out.println(account);
				
				//假设通过账号找到了角色信息   一个用户可以有多个角色
				Set<String> roles = new HashSet<>();
				//通过角色查询角色对应的权限信息
				Set<String>perms = new HashSet<>();
				
				User1 user = userService.findRolesAndPerms(account);
				//将user中的角色信息放到roles集合中
				for (Role1 role : user.getRoles()) {
					//角色
					roles.add(role.getRname());
					for (Perms1 p : role.getPerms()) {
						//权限
						perms.add(p.getPname());
					}
				}
				
				//授权info
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				info.setRoles(roles);
				info.setStringPermissions(perms);
				
				return info;
	}
	
	//获取认证(判断账号密码)的信息(账号密码)
	//如果方法返回null，表示没找到对应的账号，shiro就会报账号不存在异常
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("正在进行认证....");
		//获取到账号，然后通过账号作为查询条件到数据库中查询账号信息（账号、密码等）
		String account = (String)token.getPrincipal();
		String pwd = new String((char[])token.getCredentials());// char[]
		System.out.println(account+","+pwd);
		
		//调用service方法查询数据库
		//假设通过账号找到了一下信息
		//userService.findUserByAcount(account);
		//User user = new User().setAccount("admin").setPwd("980b4de97c8a074c423649cca19c33af");
		
		User1 user = userService.findUserByAccount(account);
		if (user == null) {
			return null;
		}
		
		//创建认证info对象
		SimpleAuthenticationInfo info = 
				new SimpleAuthenticationInfo(user.getAccount(), user.getPwd(), getName());
		return info;
	}

}
